package de.gis;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.json.JSONObject;

import android.content.SharedPreferences;
import android.util.Log;

public class DatabaseCreator extends CouchCommunicator {

	public DatabaseCreator(String dbUrl, SharedPreferences prefs) {
		super(dbUrl, prefs);
	}

	private static final String TAG = "DatabaseCreator";

	@Override
	public void doit() throws Exception {
		createDB();
		createUser();
	}

	public void createDB() throws Exception {
		Log.d(TAG, "Creating DB");
		HttpPut request = createHttpPut(dbUrl+ImageLocator.DATABASE);
		JSONObject response = getResponse(request);
		Log.d(TAG, "Creating DB result: " + response.toString());
		if (response.has("error")) {
			if (response.has("reason")) {
				throw new Exception("Could not create database " + dbUrl + ": "
						+ response.getString("reason"));
			} else {
				throw new Exception(
						"Could not create database for an unkown reason.");
			}
		}

	}

	private void createUser() throws Exception {
		// replication includes the validation method, which requires a valid
		// user
		Log.d(TAG, "Creating User 'butterfly'");
		HttpPost request = createHttpPost(dbUrl + "_users");
		String content = "{\"name\":\"butterfly\",\"roles\":[\"butterfly\"],\"_id\":\"org.couchdb.user:butterfly\",\"salt\":\"13rt\",\"password_sha\":\"c0c192be781cbace09c9bd7afd3d82b842647e8e\",\"type\":\"user\"}";
		addJson(request, content);
		getResponse(request);
	}

}
